Imports System
Imports System.Web.Management
Imports System.Configuration.Provider
Imports System.Collections.Specialized
Imports System.Web.Hosting
Imports System.IO
Imports System.Security.Permissions
Imports System.Web

Public Class FileWebEventProvider
    Inherits BufferedWebEventProvider

    Private _LogFileName As String

    Public Overrides Sub Initialize(ByVal name As String, ByVal config As NameValueCollection)
        ' Verify that config isn't null
        If (config Is Nothing) Then
            Throw New ArgumentNullException("config")
        End If
        If String.IsNullOrEmpty(name) Then
            name = "BufferedTextFileWebEventProvider"
        End If
        ' Add a default "description" attribute to config if the
        ' attribute doesn't exist or is empty
        If String.IsNullOrEmpty(config("description")) Then
            config.Remove("description")
            config.Add("description", "Buffered text file Web event provider")
        End If
        ' Initialize _LogFileName. NOTE: Do this BEFORE calling the
        ' base class's Initialize method. BufferedWebEventProvider's
        ' Initialize method checks for unrecognized attributes and
        ' throws an exception if it finds any. If we don't process
        ' logFileName and remove it from config, base.Initialize will
        ' throw an exception.
        Dim path As String = config("logFileName")
        If String.IsNullOrEmpty(path) Then
            Throw New ProviderException("Missing logFileName attribute")
        End If
        If Not VirtualPathUtility.IsAppRelative(path) Then
            Throw New ArgumentException("logFileName must be app-relative")
        End If
        Dim fullyQualifiedPath As String = VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), path)
        _LogFileName = HostingEnvironment.MapPath(fullyQualifiedPath)
        config.Remove("logFileName")
        ' Make sure we have permission to write to the log file
        ' throw an exception if we don't
        Dim permission As FileIOPermission = New FileIOPermission((FileIOPermissionAccess.Write Or FileIOPermissionAccess.Append), _LogFileName)
        permission.Demand()
        ' Call the base class's Initialize method
        MyBase.Initialize(name, config)
        ' NOTE: No need to check for unrecognized attributes
        ' here because base.Initialize has already done it
    End Sub

    Public Overrides Sub ProcessEvent(ByVal raisedEvent As WebBaseEvent)
        If UseBuffering Then
            ' If buffering is enabled, call the base class's
            ' ProcessEvent method to buffer the event
            MyBase.ProcessEvent(raisedEvent)
        Else
            ' If buffering is not enabled, log the Web event now
            LogEntry(FormatEntry(raisedEvent))
        End If
    End Sub

    Public Overrides Sub ProcessEventFlush(ByVal flushInfo As WebEventBufferFlushInfo)
        ' Log the events buffered in flushInfo.Events
        For Each raisedEvent As WebBaseEvent In flushInfo.Events
            LogEntry(FormatEntry(raisedEvent))
        Next
    End Sub

    Public Overrides Sub Shutdown()
        Flush()
    End Sub

    ' Helper methods
    Private Function FormatEntry(ByVal e As WebBaseEvent) As String
        Return String.Format("{0}{1}{2} (Event Code: {3})", e.EventTime, e.GetType.ToString, e.Message, e.EventCode)
    End Function

    Private Sub LogEntry(ByVal entry As String)
        Dim writer As StreamWriter = Nothing
        Try
            writer = New StreamWriter(_LogFileName, True)
            writer.WriteLine(entry)
        Finally
            If (Not (writer) Is Nothing) Then
                writer.Close()
            End If
        End Try
    End Sub
End Class
